package com.zhugang.week13.binarysearch;

/**
 * @program algorithms
 * @description: binarySearchFirstEquals
 * @author: chanzhugang
 * @create: 2022/11/25 13:20
 */
public class BinarySearchFirstEquals {

    /**
     * 查找第一个值等于给定元素的下标, 有重复元素
     * [1,3,5,6,6,8,10]
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bsearchFirst(int[] a, int n, int target) {
        /**
         * 套二分模版
         */
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] == target) {
                if (mid == 0 || a[mid - 1] != target) {
                    // 真命中，mid == 0，直接是第一个
                    // 找到了相等元素，但不确定是否是第一个，所以向前探测(不满足则当前下标是第一个元素的下标)
                    return mid;
                } else {
                    // 伪命中，还需要向前探测
                    high = mid - 1;
                }
            } else if (a[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchFirstEquals binarySearchFirstEquals = new BinarySearchFirstEquals();
        int[] a = {1, 3, 5, 6, 6, 8, 10};
        int index = binarySearchFirstEquals.bsearchFirst(a, a.length, 6);
        System.out.println(index);
    }
}